local CANGJIE_HOME = vim.g.CANGJIE_HOME

local isWindows = vim.fn.has("win32") == 1 or vim.fn.has("win64") == 1
local pathSep = isWindows and "\\" or "/"
local pathDelim = isWindows and ";" or ":"
local debuggerServer = table.concat({CANGJIE_HOME, "debugger", "bin", "dap_server-linux_x64"}, pathSep)
local port = vim.g.port_cangjie_debugger_server

return {
	"mfussenegger/nvim-dap",
	dependencies = {
		"theHamsta/nvim-dap-virtual-text",
		"rcarriga/nvim-dap-ui",
		"nvim-neotest/nvim-nio",
	},
	config = function()
		local dap = require("dap")
		local dapui = require("dapui")
		dap.adapters.cangjieDebug = {
			type = "server",
			port = port,
			name = "Cangjie Debugger Server",
			executable = {
				command = "bash",
				args = {
					"-c",
					table.concat({
						"LD_LIBRARY_PATH=" .. table.concat({CANGJIE_HOME, "third_party", "llvm", "lib"}, pathSep),
						debuggerServer,
						"--port=" .. port,
						"--debuggertype=lldbapi",
-- 						"--logpath=/home/vchs6/.cangjie/debug/logs/server",
					}, " "),
				},
			},
		}
		dap.configurations.cangjie = {
			{
				name = "Launch Cangjie",
				type = "cangjieDebug",
				request = "launch",
				-- 自动检测可执行文件
				program = function()
					return vim.fn.input("Path to executable: ", vim.fn.getcwd() .. "/", "file")
				end,
				cwd = "${workspaceFolder}",
				args = {},
				env = {
					LD_LIBRARY_PATH = table.concat({
						table.concat({CANGJIE_HOME, "third_party", "llvm", "lib"}, pathSep),
						CANGJIE_HOME .. pathSep .. "lib",
						CANGJIE_HOME .. pathSep .. "lib" .. pathSep .. "linux_x86_64_llvm",
						CANGJIE_HOME .. pathSep .. "tools" .. pathSep .. "lib",
						table.concat({CANGJIE_HOME, "runtime", "lib", "linux_x86_64_llvm"}, pathSep),
						vim.env.LD_LIBRARY_PATH or "",
					}, pathDelim),
					PATH = table.concat({
						vim.env.path or "",
						CANGJIE_HOME .. "bin",
						CANGJIE_HOME .. pathSep .. "tool" .. pathSep .. "sbin",
					}, pathDelim),
				},
				stopAtEntry = false,
				runInTerminal = true,
				setupCommands = {
					{
						text = "-enable-pretty-printing",
						description = "enable pretty printing",
						ignoreFailures = false,
					},
				},
			},
		}
		-- DAP UI 配置
		dapui.setup({
			icons = { expanded = "▾", collapsed = "▸", current_frame = "▶" },
			controls = {
				enabled = true,
				element = "repl",
				icons = {
					pause = "⏸️", -- Icon for pause
					play = "▶️", -- Icon for play
					step_over = "➞", -- Icon for step over
					step_into = "➤", -- Icon for step into
					step_out = "⏎", -- Icon for step out
					terminate = "🛑", -- Icon for terminate
					run_last = "🔄", -- Icon for run last
					step_back = "◀️", -- Icon for step back
				},
			},
			mappings = {
				expand = { "<CR>", "<2-LeftMouse>" },
				open = "o",
				remove = "d",
				edit = "e",
				repl = "r",
				toggle = "t",
			},
			layouts = {
				{
					elements = {
						{ id = "scopes", size = 0.25 },
						"breakpoints",
						"stacks",
						"watches",
					},
					size = 50,
					position = "left",
				},
				{
					elements = {
						"repl",
						"console",
					},
					size = 10,
					position = "bottom",
				},
			},
			-- Required fields
			element_mappings = {
				scopes = { open = "o", remove = "d" },
				breakpoints = { toggle = "t", remove = "d" },
				stacks = { open = "o", remove = "d" },
				watches = { edit = "e", remove = "d" },
			},
			expand_lines = true,
			force_buffers = true,
			floating = {
				border = "rounded",
				max_height = 0.8,
				max_width = 0.8,
				mappings = {
					close = { "q", "<Esc>" },
				},
			},
			render = {
				border = "rounded",
				max_height = 0.8,
				max_width = 0.8,
				indent = 4,
			},
		})
		require("nvim-dap-virtual-text").setup({
			enabled = true,
			enable_commands = true,
			highlight_changed_variables = true,
			highlight_new_as_changed = true,
			highlighted = true,
			virt_text_pos = "eol",
			all_frames = false,
			virt_lines = false,
			show_stop_reason = true,
			commented = false,
			only_first_definition = false,
			only_current_definition = false,
			all_references = true,
			clear_on_continue = true,
			separator = " = ",
			filter_references_pattern = ".*",
			text_prefix = "Text:",
			error_prefix = "Error:",
			info_prefix = "Info:",
			virt_lines_above = true,
			display_callback = function(variable, _buf, _stackframe, _node)
				return variable.name .. " = " .. variable.value
			end,
		})
		-- 自动打开/关闭 UI
		dap.listeners.after.event_initialized["dapui_config"] = function()
			dapui.open()
		end
		dap.listeners.before.event_terminated["dapui_config"] = function()
			dapui.close()
		end
		dap.listeners.before.event_exited["dapui_config"] = function()
			dapui.close()
		end
		-- 快捷键配置
		vim.keymap.set("n", "<F5>", dap.continue, { desc = "Start/Continue Debugging" })
		vim.keymap.set("n", "<F9>", dap.toggle_breakpoint, { desc = "Toggle Breakpoint" })
		vim.keymap.set("n", "<F10>", dap.step_over, { desc = "Step Over" })
		vim.keymap.set("n", "<F11>", dap.step_into, { desc = "Step Into" })
		vim.keymap.set("n", "<F12>", dap.step_out, { desc = "Step Out" })
		vim.keymap.set("n", "<Leader>dr", dap.repl.open, { desc = "Open REPL" })
		vim.keymap.set("n", "<Leader>dui", dapui.toggle, { desc = "Toggle Debug UI" })
		vim.keymap.set("n", "<Leader>dc", dap.close, { desc = "Close Session" })
		-- 高级快捷键
		vim.keymap.set("n", "<Leader>dB", function()
			dap.set_breakpoint(vim.fn.input("Breakpoint condition: "))
		end, { desc = "Conditional Breakpoint" })
		vim.keymap.set("n", "<Leader>dlp", function()
			local session = dap.session()
			if session then
				print(session.config.name)
			else
				print("No active DAP session.")
			end
		end, { desc = "Print Launch Program" })
	end,
}